package com.jourwon.spring.boot.service.impl;

import com.alibaba.fastjson.JSON;
import com.jourwon.spring.boot.model.vo.UserVO;
import com.jourwon.spring.boot.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.retry.RetryCallback;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户service实现类
 *
 * @author JourWon
 * @date 2021/2/6
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    private static final String URL_PREFIX = "http://127.0.0.1:8080/user/";

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private RetryTemplate retryTemplate;

    @Override
    public List<UserVO> listUsers() {
        try {
            retryTemplate.execute(
                    // RetryCallback 重试回调方法，需要重试的代码
                    (RetryCallback<List<UserVO>, IllegalAccessException>) context -> listUsersRemote(),
                    //  RecoveryCallback 异常回调方法，重试失败后执行的代码
                    context -> {
                    log.info("RecoveryCallback....");
                    return null;
            });
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<UserVO> listUsersAnotation() {
        return listUsersRemote();
    }

    private List<UserVO> listUsersRemote() {
        log.info("调用远程服务获取用户列表...");
        String url = URL_PREFIX;
        List<UserVO> list = restTemplate.getForObject(url, List.class);
        log.info("返回结果:{}", JSON.toJSONString(list));
        return list;
    }

}
